﻿#include<stdio.h>
#include<windows.h>
#include<conio.h>
#include<stdlib.h>

int position_x, position_y;//飞机位置
int bullet_x, bullet_y;//子弹位置
int high, width;//边界
int enemy_x, enemy_y;//敌机
int score;//游戏得分
static int spd;//初始速度
void gotoxy(int x, int y)
{
	HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
	COORD pos;
	pos.X = x;
	pos.Y = y;
	SetConsoleCursorPosition(handle, pos);
}

void HideCursor()//隐藏光标
{
	CONSOLE_CURSOR_INFO cursor_info = { 1,0 };
	SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);

}

void startup()     //数据初始化
{
	HideCursor();

	high = 18;
	width = 30;

	position_x = high / 2;
	position_y = width / 2;

	bullet_y = position_y;
	bullet_x = -1;

	enemy_x = 1;
	enemy_y = 5;

	score = 0;

	spd = 30;
}

void show()
{
	int i, j;

	gotoxy(0, 0);

	for (i = 0; i <= high+2; i++)
	{
		for (j = 0; j <= width+2; j++)
		{
			if ((i == position_x) && (j == position_y))
				printf("*");//输出第一行*
			if ((i == position_x+1) && (j==position_y-2))
				printf("*****");//第二行
			if ((i == position_x+2) && (j==position_y-1))
				printf("* *");
			else if ((i == bullet_x) && (j == bullet_y))
				printf("|");//输出子弹
			else if ((i == enemy_x) && (j == enemy_y))
				printf("$");//输出敌机
			else
				printf(" ");//输出空格
		}
		printf("\n");
	}
	printf("score=%d", score);
}

void updateWithoutInput()
{
	if ((bullet_x == enemy_x) && (bullet_y == enemy_y))
	{
		score++;
		spd--;
		enemy_x = 0;
		enemy_y = 2+rand() % (width-2);
		bullet_x = -1;
	}

	if (bullet_x > -1)
	{
		bullet_x--;
	}

	static int speed = 0;
	if (speed < spd)
		speed++;
	if (speed == spd)
	{
		if (enemy_x > high)
		{
			enemy_x = 0;
			enemy_y = rand() % width;
		}
		else
			enemy_x++;
		speed = 0;
	}
}
void updateWithInput()
{
	char input;
	if (kbhit())
	{
		input = getch();
		if ((input == 'a')&&(position_y>2))
			position_y--;
		else if ((input == 'd')&&(position_y<width))
			position_y++;
		else if ((input == 'w')&&(position_x>2))
			position_x--;
		else if ((input == 's')&&(position_x<high))
			position_x++;
		else if (input == ' ')
		{
			bullet_x = position_x - 1;
			bullet_y = position_y;
		}
		else if (input == 27)
		{
			while (1)
			{
				if(kbhit())
				{
					input = getch();
					if (input == 27)
						break;
				}
			}
		}
	}
}

int main()
{
	startup();
	while (1)
	{
		show();
		updateWithoutInput();
		updateWithInput();
	}
	return 0;
}